
package exchange.netserver;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Logger;

import exchange.core.Mail;
import exchange.core.Parser;
import exchange.util.ParseException;

public class ConnectionHandler implements Runnable {
	private static Logger log = Logger.getLogger(ConnectionHandler.class.getName());
	private Socket connection;
	private ObjectOutputStream outputStream;
	private ObjectInputStream inputStream;
	private String message;

	public ConnectionHandler(Socket socket) {
		connection = socket;
	}
	
	@Override
	public void run() {
		try {
			outputStream = new ObjectOutputStream(connection.getOutputStream());
			outputStream.flush();
			inputStream = new ObjectInputStream(connection.getInputStream());

			clientInteraction();
			
		} catch (SocketException e) {
			log.info("server>Disconnected " + connection.toString());
		} catch (EOFException eofExc) {
			log.warning(eofExc.getMessage() + " EOF");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		finally {
			try {
				inputStream.close();
				outputStream.close();
				connection.close();
			} catch (SocketException socExc){
				System.out.println("connection closed");
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	public void clientInteraction() throws IOException {
		Parser parser = new Parser(outputStream);
		do {
			try {
				message = (String) inputStream.readObject();
				log.info("client>" + message);
				parser.execute(message);
				
			} catch (ClassNotFoundException classnot) {
				log.warning("Data received in unknown format");
			} catch (ParseException parseExc){
				log.warning("PARSE ERROR");
				Mail.send(outputStream, parseExc.getMessage() );
			}
		
		} while (!message.equals("LOGOUT"));
	}

}
